{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2020 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aalPefrUUplk"
      },
      "source": [
        "# Introduction to Fairness Indicators"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/responsible_ai/fairness_indicators/tutorials/Fairness_Indicators_Example_Colab\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/fairness-indicators/blob/master/g3doc/tutorials/Fairness_Indicators_Example_Colab.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/fairness-indicators/blob/master/g3doc/tutorials/Fairness_Indicators_Example_Colab.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/fairness-indicators/g3doc/tutorials/Fairness_Indicators_Example_Colab.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://tfhub.dev/google/random-nnlm-en-dim128/1\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/hub_logo_32px.png\" /\u003eSee TF Hub model\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YWcPbUNg1yez"
      },
      "source": [
        "## Overview\n",
        "\n",
        "Fairness Indicators is a suite of tools built on top of [TensorFlow Model Analysis (TFMA)](https://www.tensorflow.org/tfx/model_analysis/get_started) that enable regular evaluation of fairness metrics in product pipelines. TFMA is a library for evaluating both TensorFlow and non-TensorFlow machine learning models. It allows you to evaluate your models on large amounts of data in a distributed manner, compute in-graph and other metrics over different slices of data, and visualize them in notebooks. \n",
        "\n",
        "Fairness Indicators is packaged with [TensorFlow Data Validation (TFDV)](https://www.tensorflow.org/tfx/data_validation/get_started) and the [What-If Tool](https://pair-code.github.io/what-if-tool/). Using Fairness Indicators allows you to: \n",
        "\n",
        "* Evaluate model performance, sliced across defined groups of users\n",
        "* Gain confidence about results with confidence intervals and evaluations at multiple thresholds\n",
        "* Evaluate the distribution of datasets\n",
        "* Dive deep into individual slices to explore root causes and opportunities for improvement\n",
        "\n",
        "In this notebook, you will use Fairness Indicators to fix fairness issues in a model you train using the [Civil Comments dataset](https://www.kaggle.com/c/jigsaw-unintended-bias-in-toxicity-classification). Watch this [video](https://www.youtube.com/watch?v=pHT-ImFXPQo) for more details and context on the real-world scenario this is based on which is also one of primary motivations for creating Fairness Indicators."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GjuCFktB2IJW"
      },
      "source": [
        "## Dataset\n",
        "\n",
        "In this notebook, you will work with the [Civil Comments dataset](https://www.kaggle.com/c/jigsaw-unintended-bias-in-toxicity-classification), approximately 2 million public comments made public by the [Civil Comments platform](https://medium.com/@aja_15265/saying-goodbye-to-civil-comments-41859d3a2b1d) in 2017 for ongoing research. This effort was sponsored by [Jigsaw](https://jigsaw.google.com/), who have hosted competitions on Kaggle to help classify toxic comments as well as minimize unintended model bias.\n",
        "\n",
        "Each individual text comment in the dataset has a toxicity label, with the label being 1 if the comment is toxic and 0 if the comment is non-toxic. Within the data, a subset of comments are labeled with a variety of identity attributes, including categories for gender, sexual orientation, religion, and race or ethnicity."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "u33JXdluZ2lG"
      },
      "source": [
        "## Setup\n",
        "\n",
        "Install `fairness-indicators` and `witwidget`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EoRNffG599XP"
      },
      "outputs": [],
      "source": [
        "!pip install -q -U pip==20.2\n",
        "\n",
        "!pip install -q fairness-indicators\n",
        "!pip install -q witwidget"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "alYUSbyv59j5"
      },
      "source": [
        "You must restart the Colab runtime after installing. Select **Runtime \u003e Restart** runtime from the Colab menu.\n",
        "\n",
        "Do not proceed with the rest of this tutorial without first restarting the runtime."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RbRUqXDm6f1N"
      },
      "source": [
        "Import all other required libraries."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "B8dlyTyiTe-9"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import tempfile\n",
        "import apache_beam as beam\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "from datetime import datetime\n",
        "import pprint\n",
        "\n",
        "from google.protobuf import text_format\n",
        "\n",
        "import tensorflow_hub as hub\n",
        "import tensorflow as tf\n",
        
        "import tensorflow_model_analysis as tfma\n",
        "import tensorflow_data_validation as tfdv\n",
        "\n",
        "from tfx_bsl.tfxio import tensor_adapter\n",
        "from tfx_bsl.tfxio import tf_example_record\n",
        "\n",
        "from tensorflow_model_analysis.addons.fairness.post_export_metrics import fairness_indicators\n",
        "from tensorflow_model_analysis.addons.fairness.view import widget_view\n",
        "\n",
        "from fairness_indicators.tutorial_utils import util\n",
        "\n",
        "from witwidget.notebook.visualization import WitConfigBuilder\n",
        "from witwidget.notebook.visualization import WitWidget\n",
        "\n",
        "from tensorflow_metadata.proto.v0 import schema_pb2"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TsplOJGqWCf5"
      },
      "source": [
        "## Download and analyze the data\n",
        "\n",
        "By default, this notebook downloads a preprocessed version of this dataset, but you may use the original dataset and re-run the processing steps if desired. In the original dataset, each comment is labeled with the percentage of raters who believed that a comment corresponds to a particular identity. For example, a comment might be labeled with the following: { male: 0.3, female: 1.0, transgender: 0.0, heterosexual: 0.8, homosexual_gay_or_lesbian: 1.0 } The processing step groups identity by category (gender, sexual_orientation, etc.) and removes identities with a score less than 0.5. So the example above would be converted to the following: of raters who believed that a comment corresponds to a particular identity. For example, the comment would be labeled with the following: { gender: [female], sexual_orientation: [heterosexual, homosexual_gay_or_lesbian] }"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qmt4gkBFRBD2"
      },
      "outputs": [],
      "source": [
        "download_original_data = False #@param {type:\"boolean\"}\n",
        "\n",
        "if download_original_data:\n",
        "  train_tf_file = tf.keras.utils.get_file('train_tf.tfrecord',\n",
        "                                          'https://storage.googleapis.com/civil_comments_dataset/train_tf.tfrecord')\n",
        "  validate_tf_file = tf.keras.utils.get_file('validate_tf.tfrecord',\n",
        "                                             'https://storage.googleapis.com/civil_comments_dataset/validate_tf.tfrecord')\n",
        "\n",
        "  # The identity terms list will be grouped together by their categories\n",
        "  # (see 'IDENTITY_COLUMNS') on threshould 0.5. Only the identity term column,\n",
        "  # text column and label column will be kept after processing.\n",
        "  train_tf_file = util.convert_comments_data(train_tf_file)\n",
        "  validate_tf_file = util.convert_comments_data(validate_tf_file)\n",
        "\n",
        "else:\n",
        "  train_tf_file = tf.keras.utils.get_file('train_tf_processed.tfrecord',\n",
        "                                          'https://storage.googleapis.com/civil_comments_dataset/train_tf_processed.tfrecord')\n",
        "  validate_tf_file = tf.keras.utils.get_file('validate_tf_processed.tfrecord',\n",
        "                                             'https://storage.googleapis.com/civil_comments_dataset/validate_tf_processed.tfrecord')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vFOQ4AaIcAn2"
      },
      "source": [
        "Use TFDV to analyze the data and find potential problems in it, such as missing values and data imbalances, that can lead to fairness disparities."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NdLBi6tN5i7I"
      },
      "outputs": [],
      "source": [
        "stats = tfdv.generate_statistics_from_tfrecord(data_location=train_tf_file)\n",
        "tfdv.visualize_statistics(stats)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AS9QiA96GXDE"
      },
      "source": [
        "TFDV shows that there are some significant imbalances in the data which could lead to biased model outcomes. \n",
        "\n",
        "* The toxicity label (the value predicted by the model) is unbalanced. Only 8% of the examples in the training set are toxic, which means that a classifier could get 92% accuracy by predicting that all comments are non-toxic.\n",
        "\n",
        "* In the fields relating to identity terms, only 6.6k out of the 1.08 million (0.61%) training examples deal with homosexuality, and those related to bisexuality are even more rare. This indicates that performance on these slices may suffer due to lack of training data."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9ekzb7vVnPCc"
      },
      "source": [
        "## Prepare the data\n",
        "\n",
        "Define a feature map to parse the data. Each example will have a label, comment text, and identity features `sexual orientation`, `gender`, `religion`, `race`, and `disability` that are associated with the text."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "n4_nXQDykX6W"
      },
      "outputs": [],
      "source": [
        "BASE_DIR = tempfile.gettempdir()\n",
        "\n",
        "TEXT_FEATURE = 'comment_text'\n",
        "LABEL = 'toxicity'\n",
        "FEATURE_MAP = {\n",
        "    # Label:\n",
        "    LABEL: tf.io.FixedLenFeature([], tf.float32),\n",
        "    # Text:\n",
        "    TEXT_FEATURE:  tf.io.FixedLenFeature([], tf.string),\n",
        "\n",
        "    # Identities:\n",
        "    'sexual_orientation':tf.io.VarLenFeature(tf.string),\n",
        "    'gender':tf.io.VarLenFeature(tf.string),\n",
        "    'religion':tf.io.VarLenFeature(tf.string),\n",
        "    'race':tf.io.VarLenFeature(tf.string),\n",
        "    'disability':tf.io.VarLenFeature(tf.string),\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1B1ROCM__y8C"
      },
      "source": [
        "Next, set up an input function to feed data into the model. Add a weight column to each example and upweight the toxic examples to account for the class imbalance identified by the TFDV. Use only identity features during the evaluation phase, as only the comments are fed into the model during training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YwoC-dzEDid3"
      },
      "outputs": [],
      "source": [
        "def train_input_fn():\n",
        "  def parse_function(serialized):\n",
        "    parsed_example = tf.io.parse_single_example(\n",
        "        serialized=serialized, features=FEATURE_MAP)\n",
        "    # Adds a weight column to deal with unbalanced classes.\n",
        "    parsed_example['weight'] = tf.add(parsed_example[LABEL], 0.1)\n",
        "    return (parsed_example,\n",
        "            parsed_example[LABEL])\n",
        "  train_dataset = tf.data.TFRecordDataset(\n",
        "      filenames=[train_tf_file]).map(parse_function).batch(512)\n",
        "  return train_dataset"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mfbgerCsEOmN"
      },
      "source": [
        "## Train the model\n",
        "\n",
        "Create and train a deep learning model on the data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JaGvNrVijfws"
      },
      "outputs": [],
      "source": [
        "model_dir = os.path.join(BASE_DIR, 'train', datetime.now().strftime(\n",
        "    \"%Y%m%d-%H%M%S\"))\n",
        "\n",
        "embedded_text_feature_column = hub.text_embedding_column(\n",
        "    key=TEXT_FEATURE,\n",
        "    module_spec='https://tfhub.dev/google/nnlm-en-dim128/1')\n",
        "\n",
        "classifier = tf.estimator.DNNClassifier(\n",
        "    hidden_units=[500, 100],\n",
        "    weight_column='weight',\n",
        "    feature_columns=[embedded_text_feature_column],\n",
        "    optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.003),\n",
        "    loss_reduction=tf.losses.Reduction.SUM,\n",
        "    n_classes=2,\n",
        "    model_dir=model_dir)\n",
        "\n",
        "classifier.train(input_fn=train_input_fn, steps=1000)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jTPqije9Eg5b"
      },
      "source": [
        "## Analyze the model\n",
        "\n",
        "After obtaining the trained model, analyze it to compute fairness metrics using TFMA and Fairness Indicators. Begin by exporting the model as a [SavedModel](https://www.tensorflow.org/guide/saved_model). "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-vRc-Jyp8dRm"
      },
      "source": [
        "### Export SavedModel"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QLjiy5VCzlRw"
      },
      "outputs": [],
      "source": [
        "def eval_input_receiver_fn():\n",
        "  serialized_tf_example = tf.compat.v1.placeholder(\n",
        "      dtype=tf.string, shape=[None], name='input_example_placeholder')\n",
        "\n",
        "  # This *must* be a dictionary containing a single key 'examples', which\n",
        "  # points to the input placeholder.\n",
        "  receiver_tensors = {'examples': serialized_tf_example}\n",
        "\n",
        "  features = tf.io.parse_example(serialized_tf_example, FEATURE_MAP)\n",
        "  features['weight'] = tf.ones_like(features[LABEL])\n",
        "\n",
        "  return tfma.export.EvalInputReceiver(\n",
        "    features=features,\n",
        "    receiver_tensors=receiver_tensors,\n",
        "    labels=features[LABEL])\n",
        "\n",
        "tfma_export_dir = tfma.export.export_eval_savedmodel(\n",
        "  estimator=classifier,\n",
        "  export_dir_base=os.path.join(BASE_DIR, 'tfma_eval_model'),\n",
        "  eval_input_receiver_fn=eval_input_receiver_fn)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3j8ODcee8rQ8"
      },
      "source": [
        "### Compute Fairness Metrics\n",
        "\n",
        "Select the identity to compute metrics for and whether to run with confidence intervals using the dropdown in the panel on the right."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7shDmJbx9mqa"
      },
      "outputs": [],
      "source": [
        "#@title Fairness Indicators Computation Options\n",
        "tfma_eval_result_path = os.path.join(BASE_DIR, 'tfma_eval_result')\n",
        "\n",
        "#@markdown Modify the slice_selection for experiments on other identities.\n",
        "slice_selection = 'sexual_orientation' #@param [\"sexual_orientation\", \"gender\", \"religion\", \"race\", \"disability\"]\n",
        "print(f'Slice selection: {slice_selection}')\n",
        "#@markdown Confidence Intervals can help you make better decisions regarding your data, but as it requires computing multiple resamples, is slower particularly in the colab environment that cannot take advantage of parallelization.\n",
        "compute_confidence_intervals = False #@param {type:\"boolean\"}\n",
        "print(f'Compute confidence intervals: {compute_confidence_intervals}')\n",
        "\n",
        "# Define slices that you want the evaluation to run on.\n",
        "eval_config_pbtxt = \"\"\"\n",
        "    model_specs {\n",
        "      label_key: \"%s\"\n",
        "    }\n",
        "    metrics_specs {\n",
        "      metrics {\n",
        "        class_name: \"FairnessIndicators\"\n",
        "        config: '{ \"thresholds\": [0.1, 0.3, 0.5, 0.7, 0.9] }'\n",
        "      }\n",
        "    }\n",
        "    slicing_specs {}  # overall slice\n",
        "    slicing_specs {\n",
        "      feature_keys: [\"%s\"]\n",
        "    }\n",
        "    options {\n",
        "      compute_confidence_intervals { value: %s }\n",
        "      disabled_outputs { values: \"analysis\" }\n",
        "    }\n",
        "  \"\"\" % (LABEL, slice_selection, compute_confidence_intervals)\n",
        "eval_config = text_format.Parse(eval_config_pbtxt, tfma.EvalConfig())\n",
        "eval_shared_model = tfma.default_eval_shared_model(\n",
        "    eval_saved_model_path=tfma_export_dir)\n",
        "\n",
        "schema = text_format.Parse(\n",
        "    \"\"\"\n",
        "        tensor_representation_group {\n",
        "          key: \"\"\n",
        "          value {\n",
        "            tensor_representation {\n",
        "              key: \"comment_text\"\n",
        "              value {\n",
        "                dense_tensor {\n",
        "                  column_name: \"comment_text\"\n",
        "                  shape {}\n",
        "                }\n",
        "              }\n",
        "            }\n",
        "          }\n",
        "        }\n",
        "        feature {\n",
        "          name: \"comment_text\"\n",
        "          type: BYTES\n",
        "        }\n",
        "        feature {\n",
        "          name: \"toxicity\"\n",
        "          type: FLOAT\n",
        "        }\n",
        "        feature {\n",
        "          name: \"sexual_orientation\"\n",
        "          type: BYTES\n",
        "        }\n",
        "        feature {\n",
        "          name: \"gender\"\n",
        "          type: BYTES\n",
        "        }\n",
        "        feature {\n",
        "          name: \"religion\"\n",
        "          type: BYTES\n",
        "        }\n",
        "        feature {\n",
        "          name: \"race\"\n",
        "          type: BYTES\n",
        "        }\n",
        "        feature {\n",
        "          name: \"disability\"\n",
        "          type: BYTES\n",
        "        }\n",
        "        \"\"\", schema_pb2.Schema())\n",
        "tfxio = tf_example_record.TFExampleRecord(\n",
        "    file_pattern=validate_tf_file,\n",
        "    schema=schema,\n",
        "    raw_record_column_name=tfma.ARROW_INPUT_COLUMN)\n",
        "tensor_adapter_config = tensor_adapter.TensorAdapterConfig(\n",
        "    arrow_schema=tfxio.ArrowSchema(),\n",
        "    tensor_representations=tfxio.TensorRepresentations())\n",
        "\n",
        "with beam.Pipeline() as pipeline:\n",
        "  (pipeline\n",
        "    | 'ReadFromTFRecordToArrow' \u003e\u003e tfxio.BeamSource()\n",
        "    | 'ExtractEvaluateAndWriteResults' \u003e\u003e tfma.ExtractEvaluateAndWriteResults(\n",
        "        eval_config=eval_config,\n",
        "        eval_shared_model=eval_shared_model,\n",
        "        output_path=tfma_eval_result_path,\n",
        "        tensor_adapter_config=tensor_adapter_config))\n",
        "\n",
        "eval_result = tfma.load_eval_result(output_path=tfma_eval_result_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jtDpTBPeRw2d"
      },
      "source": [
        "### Visualize data using the What-if Tool\n",
        "\n",
        "In this section, you'll use the What-If Tool's interactive visual interface to explore and manipulate data at a micro-level.\n",
        "\n",
        "Each point on the scatter plot on the right-hand panel represents one of the examples in the subset loaded into the tool. Click on one of the points to see details about this particular example in the left-hand panel. The comment text, ground truth toxicity, and applicable identities are shown. At the bottom of this left-hand panel, you see the inference results from the model you just trained.\n",
        "\n",
        "Modify the text of the example and then click the **Run inference** button to view how your changes caused the perceived toxicity prediction to change."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wtjZo4BDlV1m"
      },
      "outputs": [],
      "source": [
        "DEFAULT_MAX_EXAMPLES = 1000\n",
        "\n",
        "# Load 100000 examples in memory. When first rendered, \n",
        "# What-If Tool should only display 1000 of these due to browser constraints.\n",
        "def wit_dataset(file, num_examples=100000):\n",
        "  dataset = tf.data.TFRecordDataset(\n",
        "      filenames=[file]).take(num_examples)\n",
        "  return [tf.train.Example.FromString(d.numpy()) for d in dataset]\n",
        "\n",
        "wit_data = wit_dataset(train_tf_file)\n",
        "config_builder = WitConfigBuilder(wit_data[:DEFAULT_MAX_EXAMPLES]).set_estimator_and_feature_spec(\n",
        "    classifier, FEATURE_MAP).set_label_vocab(['non-toxicity', LABEL]).set_target_feature(LABEL)\n",
        "wit = WitWidget(config_builder)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ktlASJQIzE3l"
      },
      "source": [
        "## Render Fairness Indicators\n",
        "\n",
        "Render the Fairness Indicators widget with the exported evaluation results.\n",
        "\n",
        "Below you will see bar charts displaying performance of each slice of the data on selected metrics. You can adjust the baseline comparison slice as well as the displayed threshold(s) using the dropdown menus at the top of the visualization. \n",
        "\n",
        "The Fairness Indicator widget is integrated with the What-If Tool rendered above. If you select one slice of the data in the bar chart, the What-If Tool will update to show you examples from the selected slice. When the data reloads in the What-If Tool above, try modifying **Color By** to **toxicity**. This can give you a visual understanding of the toxicity balance of examples by slice."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JNaNhTCTAMHm"
      },
      "outputs": [],
      "source": [
        "event_handlers={'slice-selected':\n",
        "                wit.create_selection_callback(wit_data, DEFAULT_MAX_EXAMPLES)}\n",
        "widget_view.render_fairness_indicator(eval_result=eval_result,\n",
        "                                      slicing_column=slice_selection,\n",
        "                                      event_handlers=event_handlers\n",
        "                                      )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nRuZsLr6V_fY"
      },
      "source": [
        "With this particular dataset and task, systematically higher false positive and false negative rates for certain identities can lead to negative consequences. For example, in a content moderation system, a higher-than-overall false positive rate for a certain group can lead to those voices being silenced. Thus, it is important to regularly evaluate these types of criteria as you develop and improve models, and utilize tools such as Fairness Indicators, TFDV, and WIT to help illuminate potential problems. Once you've identified fairness issues, you can experiment with new data sources, data balancing, or other techniques to improve performance on underperforming groups.\n",
        "\n",
        "See [here](https://tensorflow.org/responsible_ai/fairness_indicators/guide/guidance) for more information and guidance on how to use Fairness Indicators.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wCMEMtGfx0Ti"
      },
      "source": [
        "## Use fairness evaluation results\n",
        "\n",
        "The [`eval_result`](https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/EvalResult) object, rendered above in `render_fairness_indicator()`, has its own API that you can leverage to read TFMA results into your programs."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "z6stkMLwyfza"
      },
      "source": [
        "### Get evaluated slices and metrics\n",
        "\n",
        "Use [`get_slice_names()`](https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/EvalResult#get_slice_names) and [`get_metric_names()`](https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/EvalResult#get_metric_names) to get the evaluated slices and metrics, respectively."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eXrt7SdZyzWD"
      },
      "outputs": [],
      "source": [
        "pp = pprint.PrettyPrinter()\n",
        "\n",
        "print(\"Slices:\")\n",
        "pp.pprint(eval_result.get_slice_names())\n",
        "print(\"\\nMetrics:\")\n",
        "pp.pprint(eval_result.get_metric_names())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ctAvudY2zUu4"
      },
      "source": [
        "Use [`get_metrics_for_slice()`](https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/EvalResult#get_metrics_for_slice) to get the metrics for a particular slice as a dictionary mapping metric names to [metric values](https://github.com/tensorflow/model-analysis/blob/cdb6790dcd7a37c82afb493859b3ef4898963fee/tensorflow_model_analysis/proto/metrics_for_slice.proto#L194)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zjCxZGHmzF0R"
      },
      "outputs": [],
      "source": [
        "baseline_slice = ()\n",
        "heterosexual_slice = (('sexual_orientation', 'heterosexual'),)\n",
        "\n",
        "print(\"Baseline metric values:\")\n",
        "pp.pprint(eval_result.get_metrics_for_slice(baseline_slice))\n",
        "print(\"\\nHeterosexual metric values:\")\n",
        "pp.pprint(eval_result.get_metrics_for_slice(heterosexual_slice))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UDo3LhoR0Rq1"
      },
      "source": [
        "Use [`get_metrics_for_all_slices()`](https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/EvalResult#get_metrics_for_all_slices) to get the metrics for all slices as a dictionary mapping each slice to the corresponding metrics dictionary you obtain from running `get_metrics_for_slice()` on it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "96N2l2xI0fZd"
      },
      "outputs": [],
      "source": [
        "pp.pprint(eval_result.get_metrics_for_all_slices())"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "Fairness Indicators Example Colab.ipynb",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
